package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chagee.base.utils.PaginationData;
import com.chagee.base.utils.PaginationRequest;
import com.chagee.personnel.api.event.bo.PersonnelInfo;
import com.chagee.personnel.api.event.response.EmployeeResp;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.entity.AppealReviewerConfigurationDO;
import com.chagee.store.operation.server.feign.SystemApi;
import com.chagee.store.operation.server.feign.request.ReginRequest;
import com.chagee.store.operation.server.feign.response.SystemResponse;
import com.chagee.store.operation.server.feign.vo.ReginDate;
import com.chagee.store.operation.server.model.param.*;
import com.chagee.store.operation.server.model.vo.AppealReviewerRecordVO;
import com.chagee.store.operation.server.event.service.AppealReviewerConfigurationBaseService;
import com.chagee.store.operation.server.model.vo.EmployeeVo;
import com.google.common.collect.Sets;
import com.personnel.auth.service.PersonnelAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: yuanzhiqin
 * @description:
 * @date: 2024/6/27.
 */
@Slf4j
@Service
public class AppealReviewerBizService {

	@Resource
	private AppealReviewerConfigurationBaseService addAppealReviewerBaseService;

	@Resource
	private PersonnelAuthService personnelAuthService;

	@Resource
	private PersonalBizService personalBizService;

	@Resource
	private SystemApi systemApi;

	public void addAppealReviewer(AddAppealReviewerParam param){
		PersonnelInfo loginUser = personnelAuthService.getLoginUserInfoInWeb();
		log.info("addAppealReviewer#getLoginUserInfoInWeb:{}",loginUser);
		//数据已存在不插入
		AppealReviewerConfigurationDO appealReviewerConfigurationDO = addAppealReviewerBaseService.queryByreveiwerAndCompany(param.getReveiwerId(), param.getCompanyId());
		if (Objects.nonNull(appealReviewerConfigurationDO)){
			throw new BizException(BizErrorCode.APPEAL_REVIEWER_ALREAY_EXIST);
		}

		AppealReviewerConfigurationDO appealReviewerDO = new AppealReviewerConfigurationDO();
		BeanUtils.copyProperties(param, appealReviewerDO);
		appealReviewerDO.setUserName(loginUser.getRealName());
		appealReviewerDO.setCreateUser(String.valueOf(loginUser.getId()));
		if (StringUtils.isNotEmpty(loginUser.getDeptId())){
			appealReviewerDO.setCreateDept(loginUser.getDeptId().split(",")[0]);
		}

		List<String> cityCode = param.getCityCode();
		appealReviewerDO.setCityRegion(JSONUtil.toJsonStr(cityCode));
		addAppealReviewerBaseService.save(appealReviewerDO);
	}

	public boolean deleteAppealReviewer(String reviewerId){
		return addAppealReviewerBaseService.removeById(reviewerId);
	}

	/**
	 * 分页查询审核人信息
	 *
	 * @param request
	 * @return
	 */
	public PaginationData<AppealReviewerRecordVO> pageQueryAppealReviewer(PaginationRequest<AppealReviewerListParam> request) {
		Page<AppealReviewerConfigurationDO> page = new Page<>(request.getPageNum(), request.getPageSize());
		Page<AppealReviewerConfigurationDO> queryInspectionPage = addAppealReviewerBaseService.pageQueryAppealReviewer(request.getQueryParameter(), page);
		if (CollectionUtils.isEmpty(queryInspectionPage.getRecords())) {
			return ResponseUtil.emptyResponse(request, AppealReviewerRecordVO.class, queryInspectionPage.getTotal());
		}

		List<AppealReviewerConfigurationDO> records = queryInspectionPage.getRecords();
		List<String> cityList = records.stream().map(AppealReviewerConfigurationDO::getCityRegion).filter(StringUtils::isNotBlank).collect(Collectors.toList());

		Set<String> strings = Sets.newHashSet();
		cityList.forEach(s->{
			//["123,4324","123,4324"]
			List<String> lists = JSONObject.parseArray(s, String.class);
			strings.addAll(lists);
		});

		Set<Integer> cityRegionList = Sets.newHashSet();
		if (CollectionUtil.isNotEmpty(strings)) {
			for (String code : strings) {
				if (StringUtils.isNotBlank(code)) {
					String[] regionCode = code.split(CommonConstant.OR_STRING);
					if (regionCode.length > 0) {
						Set<Integer> codeList = Arrays.stream(regionCode).map(Integer::parseInt).collect(Collectors.toSet());
						cityRegionList.addAll(codeList);
					}
				}
			}
		}
		Map<String, String> map = new HashMap<>();
		if (CollectionUtil.isNotEmpty(cityRegionList)) {
			ReginRequest reginRequest = new ReginRequest();
			reginRequest.setCodeList(new ArrayList<>(cityRegionList));
			SystemResponse<List<ReginDate>> systemResponse = null;
			try {
				systemResponse = systemApi.reginNameListQuery(reginRequest);
			} catch (Exception e) {
				log.error("AppealReviewerBizService.pageQueryAppealReviewer error:", e);
			}
			if (Objects.nonNull(systemResponse)) {
				List<ReginDate> data = systemResponse.getData();
				if (CollectionUtil.isNotEmpty(data)) {
					map = data.stream().collect(Collectors.toMap(ReginDate::getCode, ReginDate::getName));
				}
			}
		}

		Map<String, String> finalMap = map;
		List<AppealReviewerRecordVO> list = records.stream().map(appealReviewerRecordDO -> {
			AppealReviewerRecordVO appealReviewerRecordVO = new AppealReviewerRecordVO();
			BeanUtils.copyProperties(appealReviewerRecordDO, appealReviewerRecordVO);
			appealReviewerRecordVO.setId(String.valueOf(appealReviewerRecordDO.getId()));
			appealReviewerRecordVO.setCreateUser(appealReviewerRecordDO.getUserName());
			if (StringUtils.isNotBlank(appealReviewerRecordDO.getCityRegion())) {
				List<String> lists = JSONObject.parseArray(appealReviewerRecordDO.getCityRegion(), String.class);
				StringBuilder regionInfo = new StringBuilder();
				for (String regionCode : lists) {
					String[] regionCodeList = regionCode.split(CommonConstant.OR_STRING);
					for (String code : regionCodeList) {
						String info = finalMap.get(code);
						if (StringUtils.isNotBlank(info)) {
							regionInfo.append(info);
						}
					}
					regionInfo.append(CommonConstant.SYMBOL_PAUSE);
				}
				if (regionInfo.length() > 0) {
					regionInfo.deleteCharAt(regionInfo.lastIndexOf(CommonConstant.SYMBOL_PAUSE));
					appealReviewerRecordVO.setRegion(regionInfo.toString());
				}
			}
			return appealReviewerRecordVO;
		}).collect(Collectors.toList());

		return ResponseUtil.commonResponse(request, list, queryInspectionPage.getTotal());
	}

	public PaginationData<EmployeeVo> queryReviewer(QueryReviewerParam param){
		PaginationData<EmployeeVo> data = new PaginationData<>();
		data.setPageSize(param.getPageSize());
		data.setPageNum(param.getPageNum());
		data.setTotal(0L);

		PaginationData<EmployeeResp> employeeRespData = personalBizService.queryUserListbyUserName(param.getUserName(), param.getPageNum(), param.getPageSize());
		data.setTotal(employeeRespData.getTotal());

		List<EmployeeResp> employeeResps = employeeRespData.getPageList();
		List<EmployeeVo> employeeVos = new ArrayList<>();
		if (!CollectionUtils.isEmpty(employeeResps)) {
			employeeVos = employeeResps.stream().map(employeeResp -> {
				EmployeeVo employeeVo = new EmployeeVo();
				employeeVo.setUserId(String.valueOf(employeeResp.getId()));
				employeeVo.setUserName(employeeResp.getRealName());
				employeeVo.setFeishuEmpNo(employeeResp.getFeishuEmpNo());
				employeeVo.setShowName(employeeResp.getRealName());
				if (StringUtils.isNotEmpty(employeeResp.getFeishuEmpNo())){
					employeeVo.setShowName(employeeResp.getRealName()+"("+employeeResp.getFeishuEmpNo()+")");
				}
				return employeeVo;
			}).collect(Collectors.toList());
		}
		data.setPageList(employeeVos);
		return data;
	}

	public Boolean updateAppealReviewer(UpdateAppealReviewerParam param) {
		AppealReviewerConfigurationDO appealReviewerDO = addAppealReviewerBaseService.getById(param.getId());
		if (Objects.isNull(appealReviewerDO)) {
			throw new BizException(BizErrorCode.CONFIG_NOT_ERROR);
		}
		return addAppealReviewerBaseService.update(param, appealReviewerDO);
	}

}
